import 'dart:async';

import 'package:built_collection/built_collection.dart';
import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/collection_list_item/collection_list_item.dart';
import 'package:mobile_app.core/core/domain/repositories/learning_content_repository/repository.dart';
import 'package:mobile_app.home.collections.core/core/domain/helpers/validate_custom_collection_title/helper.dart';
import 'package:mobile_app.home.core/core/domain/helpers/apply_collection_list_item_update/helper.dart';

part 'failures.dart';

part 'result.dart';

abstract class CompleteCustomCollectionRenaming {
  Either<CustomCollectionRenamingCompletionFailure, CustomCollectionRenamingCompletionResult> call({
    required String collectionTitleInput,
    required CustomCollection collection,
    required BuiltList<CollectionListItem> collectionListItems,
  });
}

class CompleteCustomCollectionRenamingImpl implements CompleteCustomCollectionRenaming {
  const CompleteCustomCollectionRenamingImpl({
    required ApplyCollectionListItemUpdate applyCollectionListItemUpdate,
    required ValidateCustomCollectionTitle validateCustomCollectionTitle,
    required LearningContentRepository learningContentRepository,
  })  : _applyCollectionListItemUpdate = applyCollectionListItemUpdate,
        _validateCustomCollectionTitle = validateCustomCollectionTitle,
        _learningContentRepository = learningContentRepository;

  final ApplyCollectionListItemUpdate _applyCollectionListItemUpdate;
  final ValidateCustomCollectionTitle _validateCustomCollectionTitle;
  final LearningContentRepository _learningContentRepository;

  @override
  Either<CustomCollectionRenamingCompletionFailure, CustomCollectionRenamingCompletionResult> call({
    required String collectionTitleInput,
    required CustomCollection collection,
    required BuiltList<CollectionListItem> collectionListItems,
  }) {
    final trimmedCollectionTitle = collectionTitleInput.trim();

    final validationError = _validateCustomCollectionTitle(
      customCollectionTitle: trimmedCollectionTitle,
    );

    if (validationError != null) {
      final failure = InvalidCollectionTitleCustomCollectionRenamingCompletionFailure(
        validationError: validationError,
      );

      return left(failure);
    }

    final updatedCollection = collection.copyWith(
      title: () => trimmedCollectionTitle,
    );

    final updatedCollectionListItems = _applyCollectionListItemUpdate(
      updatedCollectionListItem: updatedCollection,
      collectionListItems: collectionListItems,
    );

    final result = CustomCollectionRenamingCompletionResult(
      collection: updatedCollection,
      collectionListItems: updatedCollectionListItems,
    );

    unawaited(_learningContentRepository.saveCollectionListItems(
      collectionListItems: updatedCollectionListItems,
    ));

    return right(result);
  }
}
